//
//  SocialDetailVC.swift
//  BaseSwift
//
//  Created by gh on 2019/10/9.
//  Copyright © 2019 ghwang. All rights reserved.
//

import UIKit
import JXPhotoBrowser
import Kingfisher

class ImageLoadr: JXPhotoLoader {
    
    func hasCached(with url: URL?) -> Bool {
        return true
    }
    func setImage(on imageView: UIImageView, url: URL?, placeholder: UIImage?, progressBlock: @escaping (Int64, Int64) -> Void, completionHandler: @escaping () -> Void) {
        
        imageView.sd_setImage(with: url) { (a, b, c, d) in
            
            
        }
    }
}

 class JXKingfisherLoader: JXPhotoLoader {
    
    public init() {}
    
    public func hasCached(with url: URL?) -> Bool {

        return false
    }
    
    public func setImage(on imageView: UIImageView, url: URL?, placeholder: UIImage?, progressBlock: @escaping (Int64, Int64) -> Void, completionHandler: @escaping () -> Void) {
        imageView.kf.setImage(with: url, placeholder: placeholder, progressBlock: { receivedSize, totalSize in
            progressBlock(receivedSize, totalSize)
        }, completionHandler: { _, _, _, _ in
            completionHandler()
        })
    }
}

class SocialDetailVC: UIViewController {


    var topPic:TopPic?
    
    var page = 0
    
    func sendRequest(){
        
        
    }
    lazy var headerView:UIView = {
        
        var cntHeight: CGFloat = 0.0
        cntHeight = (self.topPic?.content?.stringHeightWith(fontSize: 14, width: KScreenWidth-32))!
        var hei = cntHeight+200

        let bg = UIView()
        bg.backgroundColor = UIColor.white
        bg.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: hei+200)
        let icon = UIImageView()
        bg.addSubview(icon)
        let _ = icon.sd_layout()?.widthIs(32)!.heightIs(32)!.leftSpaceToView(bg,16)!.topSpaceToView(bg,16)
        icon.sd_cornerRadius = 16
        
        icon.sd_setImage(with: URL(string:self.topPic?.userHead ?? ""), placeholderImage: UIImage(named: "默认头像"), options: .lowPriority) { (A, B, C, D) in
            
        }
        let nickLab = UILabel()
        bg.addSubview(nickLab)
        nickLab.textColor = UIColor.textTitleColorBlack
        nickLab.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight(rawValue: 0.2))
        
        if self.topPic?.userName?.phoneValidate == true{
            
            nickLab.text = self.topPic?.userName?.mobileSecure(mobile: self.topPic!.userName!)

        }else{
            
            nickLab.text = self.topPic?.userName

        }
        
        let _ = nickLab.sd_layout()?.leftSpaceToView(icon,16)!.heightIs(20)!.topSpaceToView(bg,16)!.rightSpaceToView(bg,45)
        
        let timeLab = UILabel()
        bg.addSubview(timeLab)
        timeLab.textColor = UIColor.textPlaceHolderColor
        timeLab.font = UIFont.smallerFont
        timeLab.text = self.topPic?.createTime
        let _ = timeLab.sd_layout()?.leftSpaceToView(icon,16)!.heightIs(15)!.topSpaceToView(nickLab,2)!.rightSpaceToView(bg,45)
        
        let titleLab = UILabel()
        bg.addSubview(titleLab)
        titleLab.textColor = UIColor.textTitleColorBlack
        titleLab.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight(rawValue: 0.2))
        titleLab.text = self.topPic?.title
        let _ = titleLab.sd_layout()?.leftSpaceToView(bg,16)!.autoHeightRatio(0)!.topSpaceToView(timeLab,16)!.rightSpaceToView(bg,16)
        titleLab.setMaxNumberOfLinesToShow(2)
        
        
        let contLab = UILabel()
        bg.addSubview(contLab)
        contLab.textColor = UIColor.tabbarDefaultTextColor
        contLab.font = UIFont.commonFontSmaller
        contLab.text = self.topPic?.content
        let _ = contLab.sd_layout()?.leftSpaceToView(bg,16)!.autoHeightRatio(0)!.topSpaceToView(titleLab,16)!.rightSpaceToView(bg,16)
        contLab.setMaxNumberOfLinesToShow(999)
        contLab.updateLayout()
        
        
        //有图片
        if self.topPic?.userPostingImgList.count == 0{
            
            bg.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: hei)

        }else{
            
            let photo = UIButton()
            photo.addTarget(self, action: #selector(morePhotoClick), for: .touchUpInside)
            let mod = self.topPic?.userPostingImgList.first
            bg.addSubview(photo)
            photo.sd_cornerRadius = 8
            let _ = photo.sd_layout()?.leftSpaceToView(bg,16)!.rightSpaceToView(bg,16)!.heightIs(225)?.topSpaceToView(contLab,16)

            

            photo.sd_setImage(with: URL(string:(mod?.imgUrl)!), for: .normal, placeholderImage: UIImage(named: "holder_big"), options: .allowInvalidSSLCertificates, completed: { (a, b, c, d) in
                
            })

            
            
        }


        
        return bg
    }()
    lazy var bottomView:UIView = {
        
        let bg = UIView()
        bg.backgroundColor = UIColor.white
        
        let commBtnBg = UIButton()
        commBtnBg.sd_cornerRadius = 16
        bg.addSubview(commBtnBg)
        commBtnBg.addTarget(self, action: #selector(showCommentAlert), for: .touchUpInside)
        commBtnBg.backgroundColor = UIColor.backgroundColor
        let _ = commBtnBg.sd_layout()?.widthIs(200)!.heightIs(32)!.leftSpaceToView(bg,16)?.centerYEqualToView(bg)
        let icon = UIImageView()
        icon.image = UIImage(named: "写评论")
        commBtnBg.addSubview(icon)
        let _ = icon.sd_layout()?.widthIs(14)!.heightIs(13)?.centerYEqualToView(commBtnBg)!.leftSpaceToView(commBtnBg,16)
        
        let lab = UILabel()
        lab.font = UIFont.commonFontSmaller
        lab.textColor = UIColor.tabbarDefaultTextColor
        lab.text = "说点啥..."
        commBtnBg.addSubview(lab)
        let _ = lab.sd_layout()?.leftSpaceToView(icon,10)!.heightIs(20)!.centerYEqualToView(commBtnBg)!.widthIs(75)
        
        let shareBtn = UIButton()
        shareBtn.addTarget(self, action: #selector(shareClick), for: .touchUpInside)
        shareBtn.setImage(UIImage(named: "分享"), for: .normal)
        bg.addSubview(shareBtn)
        let _ = shareBtn.sd_layout()?.rightSpaceToView(bg,16)!.centerYEqualToView(bg)!.widthIs(23)!.heightIs(22)
        
        
        
        
        let commentBtn = UIButton()
        commentBtn.setImage(UIImage(named: "评论"), for: .normal)
        commentBtn.titleLabel?.font = UIFont.smallerLessthanFont
        commentBtn.setTitleColor(UIColor.textPlaceHolderColor, for: .normal)
        commentBtn.setTitle("22", for: .normal)
        bg.addSubview(commentBtn)
        let _ = commentBtn.sd_layout()?.rightSpaceToView(shareBtn,5)?.centerYEqualToView(bg)?.widthIs(55)
        
        
        let _ = commentBtn.imageView?.sd_layout()?.widthIs(23)?.heightIs(22)?.leftSpaceToView(commentBtn,0)?.centerYEqualToView(commentBtn)
        
        let _ = commentBtn.titleLabel?.sd_layout()?.heightIs(15)?.leftSpaceToView(commentBtn.imageView,5)?.widthIs(45)?.centerYEqualToView(commentBtn)
        commentBtn.titleLabel?.textAlignment = .left
        commentBtn.isHidden = true
        
        let favBtn = UIButton()
        favBtn.addTarget(self, action: #selector(favClick), for: .touchUpInside)
         favBtn.setImage(UIImage(named: "收藏"), for: .normal)
         favBtn.titleLabel?.font = UIFont.smallerLessthanFont
         favBtn.setTitleColor(UIColor.textPlaceHolderColor, for: .normal)
         //favBtn.setTitle("18", for: .normal)
         bg.addSubview(favBtn)
         let _ = favBtn.sd_layout()?.rightSpaceToView(commentBtn,30)?.centerYEqualToView(bg)?.widthIs(55)
         
         
         let _ = favBtn.imageView?.sd_layout()?.widthIs(23)?.heightIs(22)?.rightSpaceToView(favBtn,0)?.centerYEqualToView(favBtn)
         
         let _ = favBtn.titleLabel?.sd_layout()?.heightIs(15)?.leftSpaceToView(favBtn.imageView,5)?.widthIs(45)?.centerYEqualToView(favBtn)
         favBtn.titleLabel?.textAlignment = .left
        favBtn.isHidden = true
        
        
        
        return bg
        
    }()
    lazy var tableView:UITableView = {
        
        
        var tableView = UITableView()
        tableView.dataSource = self
        tableView.delegate = self
        tableView.backgroundColor = UIColor.clear
        tableView.tableFooterView = UIView()
        tableView.separatorColor = UIColor.lineColor
        tableView.tableHeaderView = self.headerView
        tableView.showsVerticalScrollIndicator = false
        tableView.register(UINib.init(nibName: "CommentCell", bundle: nil), forCellReuseIdentifier: "CommentCell")
        return tableView
    }()
    

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.navigationView.setTitle("")
        self.view.backgroundColor = UIColor.backgroundColor
        
        self.view.addSubview(tableView)
        let _ = tableView.sd_layout()?.spaceToSuperView(UIEdgeInsets(top: HT_StatusBarAndNavigationBarHeight, left: 0, bottom: HT_TabbarSafeBottomMargin+56, right: 0))
        
        
        self.view.addSubview(self.bottomView)
        let _ = self.bottomView.sd_layout()?.widthRatioToView(self.view,1)!.heightIs(55)!.bottomSpaceToView(self.view,HT_TabbarSafeBottomMargin)
        

    }
    
    @objc func morePhotoClick(){
        
        var imgs = [String]()
        for item in self.topPic!.userPostingImgList{
            
            imgs.append(item.imgUrl!)
        }

        
        let datas = JXNetworkingDataSource(photoLoader: JXKingfisherLoader(), numberOfItems: { () -> Int in
            return imgs.count
        }, placeholder: { (num) -> UIImage? in
            
            return nil
            
        }) { (num) -> String? in
            
            return imgs.get(at: num)
        }
        
        JXPhotoBrowser(dataSource: datas).show(pageIndex: 0)
    }

    @objc func shareClick(){
        

        let img0 = BZHttpFileHelper.imageWithScreenshot()
        let img1 = BZHttpFileHelper.compressImage(img0, toByte: 50*1024)

        let shareItems:Array = [img1 as Any] as [Any]
                let activityViewController:UIActivityViewController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil)
        activityViewController.excludedActivityTypes = [UIActivity.ActivityType.print, UIActivity.ActivityType.postToWeibo, UIActivity.ActivityType.copyToPasteboard, UIActivity.ActivityType.addToReadingList, UIActivity.ActivityType.postToVimeo]
                self.present(activityViewController, animated: true, completion: nil)


    }
    
    @objc func favClick(){
        
        
//        API.collect(params: ["type":"COL",
//                             "colType":"",
//                             "pdtId":""]) { (result) in
//            
//            
//        }
    }
    
    
    
let bg = UIView()
let inputV = GCPlaceholderTextView()

    
   @objc func showCommentAlert() {
        
        self.view.addSubview(bg)
        let _  = bg.sd_layout()?.spaceToSuperView(.zero)

        let bgImgv = UIImageView()
        bgImgv.alpha = 0.5
        bgImgv.backgroundColor = UIColor.init(patternImage: UIImage(named: "paybg")!)
        bg.addSubview(bgImgv)
        let _ = bgImgv.sd_layout()?.spaceToSuperView(.zero)
        
        let bg2 = UIView()
    bg2.backgroundColor = UIColor.white
        bg.addSubview(bg2)
        let _ = bg2.sd_layout()?.bottomSpaceToView(bg,0)?.widthRatioToView(bg,1)?.heightIs(166)
    
    bg2.addSubview(inputV)
    inputV.placeholder = "发表评论"
    inputV.sd_cornerRadius = 3
    inputV.font = UIFont.commonFontSmall
    inputV.textColor = UIColor.textTitleColorBlack
    let _ = inputV.sd_layout()?.leftSpaceToView(bg2,16)!.rightSpaceToView(bg2,16)!.heightIs(90)!.topSpaceToView(bg2,25)
    inputV.layer.borderColor = UIColor.textTitleColorBlack.cgColor
    inputV.layer.borderWidth = 0.5
    
    let sendBtn = UIButton()
    sendBtn.setTitle("发送", for: .normal)
    sendBtn.addTarget(self, action: #selector(sendBtnClick), for: .touchUpInside)
    sendBtn.setTitleColor(UIColor.btnMainColor, for: .normal)
    sendBtn.titleLabel?.font = UIFont.commonFontSmall
    bg2.addSubview(sendBtn)
    
    let _ = sendBtn.sd_layout()?.rightSpaceToView(bg2,16)!.heightIs(28)!.widthIs(38)!.topSpaceToView(inputV,5)
    
    let cancelBtn = UIButton()
    cancelBtn.setTitle("取消", for: .normal)
    cancelBtn.addTarget(self, action: #selector(cancelBtnClick), for: .touchUpInside)
    cancelBtn.setTitleColor(UIColor.GP_Red_Color, for: .normal)
    cancelBtn.titleLabel?.font = UIFont.commonFontSmall
    bg2.addSubview(cancelBtn)
    
    let _ = cancelBtn.sd_layout()?.leftSpaceToView(bg2,16)!.heightIs(28)!.widthIs(38)!.topSpaceToView(inputV,5)
    
    
    
        
    }
    
    @objc func sendBtnClick(){
        
          if SPUtil.init().loginStatus == 0 {
              
              APP.backToVC = self
              PUSH(from: self, to: LoginViewController())
              return
          }
          if SPUtil.init().mobile.count == 0 {
              
              APP.backToVC = self
              PUSH(from: self, to: BindPhoneVC())
              return
        
          }
        
        if inputV.text.count == 0 {
            
            ToastUtil.showHUDWarn(msg: "随便写点什么吧")
            return
        }
        
        
        API.socialComment(params: ["pdtId":self.topPic!.id!,
                                   "mobile":SPUtil.init().mobile!,
                                   "content":inputV.text]) { (result) in
            
            
                                    ToastUtil.show(msg: "评论成功")
                                    API.socialDetail(params: ["pId":self.topPic!.id!]) { (result) in
                                        
                         
                                        self.topPic = (result as! TopPic)
                                        self.tableView.reloadData()
                                        
                                    }
                                    
            self.bg.removeFromSuperview()

        }
        
    }
    @objc func cancelBtnClick(){
        
        bg.removeFromSuperview()
    }

}
extension SocialDetailVC:UITableViewDelegate,UITableViewDataSource{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return (self.topPic?.userPostingReplyList.count)!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let mod = self.topPic?.userPostingReplyList.get(at: indexPath.row)
        let cnt = mod?.content
        let height  = cnt!.stringHeightWith(fontSize: 14, width: KScreenWidth-64-16)
        
        return 50+height+32
        
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        return 64
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let bg = UIView()
        bg.backgroundColor = UIColor.backgroundColor
        bg.backgroundColor = UIColor.white
        bg.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: 64)
        
        let line = UIView()
        line.backgroundColor = UIColor.backgroundColor
        bg.addSubview(line)
        let _ = line.sd_layout()?.heightIs(10)!.widthRatioToView(bg,1)!.topSpaceToView(bg,10)
        
        let titleLab = UILabel()
        bg.addSubview(titleLab)
        titleLab.textColor = UIColor.textTitleColorBlack
        titleLab.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight(rawValue: 0.2))
        titleLab.text = "评论"
        let _ = titleLab.sd_layout()?.leftSpaceToView(bg,16)!.heightIs(30)!.topSpaceToView(bg,10+18)!.rightSpaceToView(bg,16)
        return bg
    }
    

    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let mod = self.topPic?.userPostingReplyList.get(at: indexPath.row)

        let cell = tableView.dequeueReusableCell(withIdentifier: "CommentCell") as! CommentCell
        cell.setModel(mod: mod!)
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {


    }

    
    
}
